package org.jeecgframework.web.service.impl;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.jboss.logging.Logger;
import org.jeecgframework.core.common.model.json.AjaxJson;
import org.jeecgframework.core.common.service.impl.CommonServiceImpl;
import org.jeecgframework.core.util.DateUtils;
import org.jeecgframework.core.util.ListUtils;
import org.jeecgframework.core.util.ResourceUtil;
import org.jeecgframework.core.util.oConvertUtils;
import org.jeecgframework.web.service.CbsAppMessageServiceI;
import org.jeecgframework.web.service.ZyCommonService;
import org.jeecgframework.web.system.pojo.base.CbsAppMessageEntity;
import org.jeecgframework.web.system.pojo.base.TSUser;
import org.jeecgframework.web.util.StaticValue;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service("cbsAppMessageService")
@Transactional
public class CbsAppMessageServiceImpl extends CommonServiceImpl implements CbsAppMessageServiceI {

	private static final Logger logger = Logger.getLogger(CbsAppMessageServiceImpl.class);

	@Autowired
	ZyCommonService zyCommonService;
	
 	public <T> void delete(T entity) {
 		super.delete(entity);
 		//执行删除操作配置的sql增强
		this.doDelSql((CbsAppMessageEntity)entity);
 	}
 	
 	public <T> Serializable save(T entity) {
 		Serializable t = super.save(entity);
 		//执行新增操作配置的sql增强
 		this.doAddSql((CbsAppMessageEntity)entity);
 		return t;
 	}
 	
 	public <T> void saveOrUpdate(T entity) {
 		super.saveOrUpdate(entity);
 		//执行更新操作配置的sql增强
 		this.doUpdateSql((CbsAppMessageEntity)entity);
 	}
 	
 	/**
	 * 默认按钮-sql增强-新增操作
	 * @return
	 */
 	public boolean doAddSql(CbsAppMessageEntity t){
	 	return true;
 	}
 	/**
	 * 默认按钮-sql增强-更新操作
	 * @return
	 */
 	public boolean doUpdateSql(CbsAppMessageEntity t){
	 	return true;
 	}
 	/**
	 * 默认按钮-sql增强-删除操作
	 * @return
	 */
 	public boolean doDelSql(CbsAppMessageEntity t){
	 	return true;
 	}
 	
 	/**
	 * 替换sql中的变量
	 * @param sql
	 * @return
	 */
 	public String replaceVal(String sql,CbsAppMessageEntity t){
 		sql  = sql.replace("#{id}",String.valueOf(t.getId()));
 		sql  = sql.replace("#{content}",String.valueOf(t.getContent()));
 		sql  = sql.replace("#{sender}",String.valueOf(t.getSender()));
 		sql  = sql.replace("#{reciver}",String.valueOf(t.getReciver()));
 		sql  = sql.replace("#{create_name}",String.valueOf(t.getCreateName()));
 		sql  = sql.replace("#{create_by}",String.valueOf(t.getCreateBy()));
 		sql  = sql.replace("#{create_date}",String.valueOf(t.getCreateDate()));
 		sql  = sql.replace("#{update_name}",String.valueOf(t.getUpdateName()));
 		sql  = sql.replace("#{update_by}",String.valueOf(t.getUpdateBy()));
 		sql  = sql.replace("#{update_date}",String.valueOf(t.getUpdateDate()));
 		sql  = sql.replace("#{UUID}",UUID.randomUUID().toString());
 		return sql;
 	}
 	
 	
 	@Override
	public Integer queryAppMessageUnreadCount(HttpServletRequest req) {
 		Integer count = 0;
		TSUser user = ResourceUtil.getSessionUserName();
		if(null != user){
			StringBuffer sql = new StringBuffer();
			sql.append(" SELECT ");
			sql.append(" 	COUNT(1) AS total ");
			sql.append(" FROM ");
			sql.append(" 	cbs_app_message am ");
			sql.append("	LEFT JOIN t_s_base_user bu ON bu.id = am.sender ");
			sql.append(" WHERE ");
			sql.append(" 	am.reciver = '").append(user.getId()).append("' ");
			sql.append(" 	AND am.state = '").append(StaticValue.DIC_APP_MESSAGE_STATE_UNREAD).append("' ");
			sql.append(" ORDER BY ");
			sql.append(" 	create_date DESC ");
			count = zyCommonService.getCountBySql(sql.toString());
		}
		return count;
	}
	
	@Override
	public List<Map<String, Object>> queryAppMessage(HttpServletRequest req) {
		List<Map<String, Object>> rsMap = new ArrayList<>();
		TSUser user = ResourceUtil.getSessionUserName();
		if(null != user){
			StringBuilder sql = new StringBuilder();
			sql.append(" SELECT ");
			sql.append(" 	am.id AS amId, ");
			sql.append(" 	bu.realname, ");
			sql.append(" 	am.content, ");
			sql.append(" 	am.state, ");
			sql.append(" 	DATE_FORMAT(am.create_date,'%y-%m-%d %H:%i:%s') AS createDate ");
			sql.append(" FROM ");
			sql.append(" 	cbs_app_message am ");
			sql.append("	LEFT JOIN t_s_base_user bu ON bu.id = am.sender ");
			sql.append(" WHERE ");
			sql.append(" 	am.reciver = '").append(user.getId()).append("' ");
			sql.append(" ORDER BY ");
			sql.append(" 	create_date DESC ");
			rsMap = super.findForJdbc(sql.toString());
			if(!ListUtils.isNullOrEmpty(rsMap)){
				for(Map<String, Object> map : rsMap){
					if(null != map.get("content") && !map.get("content").toString().equals("")){
						if(map.get("content").toString().length() > 100){
							map.put("content", map.get("content").toString().substring(0,100) + "...");
						}
					}
				}
			}
		}
		
		return rsMap;
	}
	
	
	
	@Override
	public void readAppMessage(AjaxJson j, HttpServletRequest req){
		String amId = oConvertUtils.getString(req.getParameter("amId"));
		if(!"".equals(amId)){
			CbsAppMessageEntity am = super.getEntity(CbsAppMessageEntity.class, amId);
			am.setState(StaticValue.DIC_APP_MESSAGE_STATE_READ);
			super.saveOrUpdate(am);
			Map<String, String> map = new HashMap<>();
			map.put("content", am.getContent());
			map.put("createDate", DateUtils.date2Str(am.getCreateDate(), DateUtils.datetimeFormat));
			map.put("sender", am.getCreateName());
			j.setObj(map);
		}
	}

	@Override
	public void appBatchReadMessage(AjaxJson j, HttpServletRequest req) {
		try {
			String amIds = oConvertUtils.getString(req.getParameter("amIds"));
			String[] amIdsArr = amIds.split(",");
			if(amIdsArr.length > 0){
				StringBuilder amIdStr = new StringBuilder();
				for(String amId : amIdsArr){
					amIdStr.append("'" + amId + "',");
				}
				super.executeSql("UPDATE cbs_app_message SET state = ? WHERE id IN ("+ amIdStr.substring(0,amIdStr.length() - 1) +")", StaticValue.DIC_APP_MESSAGE_STATE_READ);
				j.setSuccess(true);
				j.setMsg(amIdsArr.length + "条消息设为了已读");
			}
		} catch (Exception e) {
			logger.error(e);
			e.printStackTrace();
			j.setSuccess(false);
			j.setMsg("批量设为已读失败");
		}
	}
}